package com.zjpavt.client.extenddevice.loop.extendloopcontroller;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.zjpavt.client.extenddevice.IExtendDevice;
import com.zjpavt.client.extenddevice.IVoltageAndCurrentDetection;
import com.zjpavt.client.extenddevice.helpbean.OwnerDevice;
import com.zjpavt.client.extenddevice.loop.loopcontroller.VoltageAndCurrentDetection;
import com.zjpavt.client.nativemethod.JnIMethod;
import com.zjpavt.client.util.LoggerUtil;
import com.zjpavt.client.util.NumberUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 电压电流检测模块（回路控制器内嵌的电压电流检测功能）
 * 修改相位，查询电压电流数据（U指令，电压电流显示页面） 外部调用
 * 实时获取检测模块的数据（通过485接口）
 * @author zyc
 */
@Slf4j
public class ExtendVoltageAndCurrentDetection extends VoltageAndCurrentDetection implements OwnerDevice, IVoltageAndCurrentDetection{

    public ExtendVoltageAndCurrentDetection(int loopNum, int extNum, IExtendDevice device, int slaveIndex) {
        super(loopNum, extNum, device);
        
        this.slaveIndex = slaveIndex;
    }

    public void setBeginIndex(int beginIndex) {
        this.beginIndex = beginIndex;
    }


    protected static final String SALVE_NUM = "slaveNum";
    /**
     * <AT_SLAVE_99_DATA_CH00_[A_230.0][B_230.0][C_230.0][001/49.99/1][002/49.99/1][003/49.99/1][004/49.99/1][005/49.99/1]
     * 	[006/49.99/1][007/49.99/1][008/49.99/1][009/49.99/1][010/49.99/1][011/49.99/1][012/49.99/1]>
     */
    protected static final Pattern VOLTAGE_CURRENT_PATTERN =
            Pattern.compile("<AT_SLAVE_(?<" + SALVE_NUM + ">[0-9]{0,2})_DATA__CH[0-9]{1,2}_\\[A_(?<A>\\d{1,3}\\.\\d)]\\[B_(?<B>\\d{1,3}\\.\\d)\\[C_(?<C>\\d{1,3}\\.\\d)]" +"(?:\\[[0-9]{1,3}/[0-9.]{1,5}/[01]])*>");

    /** [序列号/电流值/回路通断]     [001/11.81/1]     */
    protected static final Pattern CURRENT_PATTERN = Pattern.compile("\\[(?<index>[0-9]{1,3})/(?<current>[0-9\\.]{1,5})/(?<open>[01])]");

    /**
     * 根据检测模块更新电流电压数据
     */
    public void updateInformation() {
        String askMessage = "<AT_SLAVE_" + getFormatSlave() + "_CIRCUIT_CURRENT_DATA>";
        String message = JnIMethod.sendMessage2ExtendDeviceByRs485DefaultBanudRate( extendNum, askMessage, 200);
        if (message == null) {
            getOwnerDevice().getUnderDeviceInteractionBean().interactionFail();
            return;
        } else {
            getOwnerDevice().getUnderDeviceInteractionBean().interactionSuccess();
        }
        Matcher matcher = VOLTAGE_CURRENT_PATTERN.matcher(message);
        if (matcher.matches()) {
            try {
                voltageAPhase = Double.parseDouble(matcher.group("A"));
                voltageBPhase = Double.parseDouble(matcher.group("B"));
                voltageCPhase = Double.parseDouble(matcher.group("C"));
            } catch (NumberFormatException e) {
                log.error(LoggerUtil.convertException2String(e));
            }
        }
        Matcher currentMatcher = CURRENT_PATTERN.matcher(message);
        while (currentMatcher.find()) {
            //index从1开始
            try {
                int index = Integer.parseInt(currentMatcher.group("index"));
                double current = Double.parseDouble(currentMatcher.group("current"));
                setCurrent(current, index);
            } catch (Exception e) {
                log.error(LoggerUtil.convertException2String(e));
            }
        }
    }


    /**
     * 获取格式化的从机地址
     * @return
     */
    public String getFormatSlave() {
        return NumberUtil.getFormat00(slaveIndex);
    }
    
    /**
     * 所属从机序列号
     */
    protected int slaveIndex;
}
